import React, { useState, useEffect } from 'react';
import { DatePicker, Input, TreeSelect, Icon } from 'antd';
import PropTypes from 'prop-types';
import ArrowDownSvg from './images/arrow-down.svg';
import moment from 'moment';
import _ from 'lodash';
import cn from 'classnames';
import {
  actions as assetManageActions,
  DataRangeFilterType,
  InputFilterType,
  TreeSelectFilterType
} from '../../reducer';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import './index.less';
import { attributeFilterTargetDom } from './constant';

const RangePicker = DatePicker.RangePicker;

const ExtendAttributeFilterId = `attributer-filter_${Date.now()}`;

function formatTreeSelectOption(options = [], fieldNames = {}) {
  const {
    title: titleField = 'name',
    value: valueField = '_id',
    key: keyField = '_id',
    children: childrenField = 'children'
  } = fieldNames;
  const formatedOptions = [];
  for (const rawOption of options) {
    if (!rawOption[titleField]) {
      continue;
    }
    const option = {
      title: rawOption[titleField],
      value: rawOption[valueField],
      key: rawOption[keyField],
      item: rawOption
    };
    if (rawOption[childrenField] && rawOption[childrenField].length) {
      option.children = formatTreeSelectOption(rawOption[childrenField], fieldNames);
    }
    formatedOptions.push(option);
  }
  return formatedOptions;
}

// 筛选下拉时的输入框组件
function InputDropDownContent(props) {
  const { value = '', onChange } = props;
  const [inner, setInner] = useState(value);
  useEffect(() => {
    if (inner !== value) {
      setInner(value);
    }
  }, [value]);
  return (
    <div className="input-dropdown-content">
      <Input
        className="input"
        placeholder="搜索"
        value={inner}
        ref={function(input) {
          if (input !== null) {
            input.focus();
          }
        }}
        onChange={e => setInner(e.target.value)}
      />
      <a className="confirm" onClick={() => onChange(inner)}>
        确定
      </a>
    </div>
  );
}
InputDropDownContent.propTypes = {
  value: PropTypes.string,
  onChange: PropTypes.func
};

// 筛选项组件
class AttributeFilterItem extends React.Component {
  static propTypes = {
    title: PropTypes.string,
    key: PropTypes.string,
    type: PropTypes.string,
    options: PropTypes.array,
    active: PropTypes.bool,
    value: PropTypes.any,
    onChange: PropTypes.func,
    onClick: PropTypes.func,
    customAttributeList: PropTypes.array,
    onRemoveExtend: PropTypes.func, // 删除扩展筛选项回调
    showValue: PropTypes.bool, // 是否展示筛选值预
    isExtend: PropTypes.bool // 是否是扩展筛选项
  };
  constructor(props) {
    super(props);
    this.dropDownRef = React.createRef();
    this.id = Math.random()
      .toString()
      .replace('.', '');
  }

  componentDidMount() {
    if (this.props.type === TreeSelectFilterType) {
      this.wraper = document.querySelector(`.tree-select_${this.id}`);
      if (this.wraper) {
        this.wraper.addEventListener('click', this.handleClickSelectWrapper);
      }
    }
  }

  componentDidUpdate(preProps) {
    if (!preProps.active && this.props.active) {
      this.checkDropdownInView();
    }
  }

  componentWillUnmount() {
    if (this.wraper && this.props.type === TreeSelectFilterType) {
      this.wraper.removeEventListener('click', this.handleClickSelectWrapper);
    }
  }

  checkDropdownInView = () => {
    // 检查下拉框定位是否超出屏幕外
    if (this.dropDownRef && this.dropDownRef.current) {
      const viewWidth = window.document.body.clientWidth;
      const { right, left } = this.dropDownRef.current.getBoundingClientRect();
      if (right > viewWidth) {
        this.dropDownRef.current.style.left = 'auto';
        this.dropDownRef.current.style.right = 0;
      } else if (left < 0) {
        this.dropDownRef.current.style.left = '8px';
        this.dropDownRef.current.style.right = 'auto';
      }
    }
  };

  handleClickSelectWrapper = () => {
    const input = document.querySelector(`.tree-select_${this.id} .ant-select-search__field`);
    if (input) {
      input.focus();
    }
  };

  getDropdownContainer = () => {
    return (
      this.dropDownRef.current ||
      document.getElementById(ExtendAttributeFilterId) ||
      window.document.body
    );
  };

  renderDropdown = () => {
    const { type, options, value, onChange, active } = this.props;
    if (type === TreeSelectFilterType) {
      return (
        <TreeSelect
          className={cn('tree-select', `tree-select_${this.id}`)}
          dropdownClassName="tree-select-dropdown"
          treeData={options}
          treeDefaultExpandAll
          placeholder="搜索"
          labelInValue
          maxTagCount={10}
          showSearch
          multiple
          // treeCheckStrictly
          filterTreeNode={(input, node) => {
            return _.includes(_.toLower(node.props.title), _.toLower(input));
          }}
          value={value}
          onChange={onChange}
          treeCheckable={true}
          getPopupContainer={this.getDropdownContainer}
          open={active}
        />
      );
    } else if (type === InputFilterType) {
      return <InputDropDownContent value={value} onChange={onChange} />;
    } else if (type === DataRangeFilterType) {
      return (
        <RangePicker
          getCalendarContainer={this.getDropdownContainer}
          value={value}
          open={active}
          onChange={onChange}
          className="range-picker"
          popupStyle={{ position: 'static' }}
          dropdownClassName="range-picker-popup"
          renderExtraFooter={() => {
            return <a onClick={() => onChange([])}>重置</a>;
          }}
        />
      );
    }
    return null;
  };

  render() {
    const {
      title,
      key,
      type,
      active,
      value,
      onRemoveExtend,
      showValue = true,
      isExtend
    } = this.props;
    const valueEmpty = _.isEmpty(value);
    let valueString = '';
    if (type === TreeSelectFilterType && !valueEmpty) {
      valueString = _.map(value, 'label').join(',');
    } else if (type === InputFilterType && !valueEmpty) {
      valueString = value;
    } else if (type === DataRangeFilterType && !valueEmpty) {
      valueString = value.map(i => moment(i).format('YYYY-MM-DD')).join(' - ');
    }

    return (
      <span
        data-test={key}
        className={cn('attribute-filter-item', type, { valued: valueString, active })}
        key={key}
        onClick={this.props.onClick}
      >
        <span
          className="name attribute-filter-item-name"
          title={valueString && showValue && valueString}
        >
          {title}
          {valueString && showValue && `：${valueString}`}
        </span>
        <img className="icon attribute-filter-item-icon" src={ArrowDownSvg} />
        {/* {valueString && (
          <Icon
            title="删除筛选"
            onClick={e => {
              e.stopPropagation();
              if (!_.isEmpty(value)) {
                onChange([]);
              }
            }}
            className="clear"
            type="close-circle"
            theme="filled"
          />
        )} */}
        {isExtend && (
          <Icon
            title="删除条件"
            onClick={onRemoveExtend}
            className="remove-item"
            type="close-circle"
            theme="filled"
          />
        )}
        <div
          className={cn('attribute-filter-item-dropdown', `${type}-dropdown`, { active })}
          ref={this.dropDownRef}
        >
          {this.renderDropdown()}
        </div>
      </span>
    );
  }
}

class AttributeFilter extends React.Component {
  static propTypes = {
    customAttributeList: PropTypes.array,
    attributeFilter: PropTypes.object,
    setState: PropTypes.func,
    tags: PropTypes.array,
    areaList: PropTypes.array,
    organizationTree: PropTypes.array,
    assetCategoryTree: PropTypes.array,
    siteAttributeStats: PropTypes.object,
    assetStats: PropTypes.object,
    modules: PropTypes.array
  };
  constructor(props) {
    super(props);
    this.state = {
      activeFilterKey: '',
      criteriaFilters: this.getCriteriaFilters(),
      totalExtendFilters: this.getTotalExtendFilters(),
      extendFilters: []
    };
    this.expanTimeoutTimer = null;
  }
  componentDidMount() {
    document.addEventListener('click', this.handleClickDocument);
  }
  componentDidUpdate(prevProps) {
    if (
      prevProps.customAttributeList !== this.props.customAttributeList ||
      prevProps.assetStats !== this.props.assetStats
    ) {
      this.setState({
        totalExtendFilters: this.getTotalExtendFilters()
      });
    }
    if (prevProps.customAttributeList !== this.props.customAttributeList) {
      this.setState({
        criteriaFilters: this.getCriteriaFilters()
      });
    }
  }

  componentWillUnmount() {
    document.removeEventListener('click', this.handleClickDocument);
    if (this.expanTimeoutTimer) {
      window.clearTimeout(this.expanTimeoutTimer);
    }
  }
  // 谷歌浏览器升级导致的获取不到e的层级classname 暂时选用判断点击的是否为目标组件列表
  handleClickDocument = e => {
    if (
      e.target.className.split &&
      !e.target.className.split(' ').find(r => {
        return attributeFilterTargetDom.includes(r);
      })
    ) {
      this.setState({ activeFilterKey: '' });
    }
  };

  // 获取标准搜索项
  getCriteriaFilters = () => {
    const { customAttributeList, modules = [] } = this.props;
    const hasOneDayModule = modules.includes('1day');
    const filters = [
      {
        title: '权重',
        key: 'weight',
        type: TreeSelectFilterType,
        options: [
          {
            title: '五星',
            key: 5,
            value: 5
          },
          {
            title: '四星',
            key: 4,
            value: 4
          },
          {
            title: '三星',
            key: 3,
            value: 3
          },
          {
            title: '二星',
            key: 2,
            value: 2
          },
          {
            title: '一星',
            key: 1,
            value: 1
          }
        ]
      },
      {
        title: '端口数',
        key: 'portful',
        type: TreeSelectFilterType,
        options: [
          {
            title: '有存活端口',
            key: 'active',
            value: 'active'
          },
          {
            title: '无存活端口',
            key: 'unactive',
            value: 'unactive'
          },
          {
            title: '未知',
            key: 'unknown',
            value: 'unknown'
          }
        ]
      },
      hasOneDayModule && {
        title: '漏洞等级',
        key: 'vulLevel',
        type: TreeSelectFilterType,
        options: [
          {
            title: '严重',
            key: 'fatal',
            value: 'fatal'
          },
          {
            title: '高危',
            key: 'high',
            value: 'high'
          },
          {
            title: '中危',
            key: 'middle',
            value: 'middle'
          },
          {
            title: '低危',
            key: 'low',
            value: 'low'
          }
        ]
      },
      {
        title: 'PING 响应',
        key: 'pingable',
        type: TreeSelectFilterType,
        options: [
          {
            title: '有响应',
            key: 'active',
            value: 'active'
          },
          {
            title: '无响应',
            key: 'unactive',
            value: 'unactive'
          },
          {
            title: '未知',
            key: 'unknown',
            value: 'unknown'
          }
        ]
      },
      {
        title: '更新时间',
        key: 'updated',
        type: DataRangeFilterType
      },
      {
        title: '更多',
        key: 'moreAction',
        type: TreeSelectFilterType,
        showValue: false,
        options: [
          {
            title: '搜索条件',
            key: 'condition',
            value: 'condition',
            disableCheckbox: true,
            children: [
              {
                title: '资产分类',
                key: 'assetCategory',
                value: 'assetCategory'
              },
              {
                title: '资产类型',
                key: 'assetType',
                value: 'assetType'
              },
              {
                title: '部门',
                key: 'organization',
                value: 'organization'
              },
              {
                title: '地理位置',
                key: 'location',
                value: 'location'
              },
              {
                title: '操作系统',
                key: 'os',
                value: 'os'
              },
              {
                title: '端口',
                key: 'port',
                value: 'port'
              },
              {
                title: '服务',
                key: 'service',
                value: 'service'
              },
              {
                title: '组件',
                key: 'component',
                value: 'component'
              },
              {
                title: '防护信息',
                key: 'waf',
                value: 'waf'
              },
              hasOneDayModule && {
                title: '漏洞',
                key: 'oneday',
                value: 'oneday'
              },
              {
                title: '标签',
                key: 'tag',
                value: 'tag'
              },
              {
                title: '区域编码',
                key: 'areaCode',
                value: 'areaCode'
              },
              {
                title: '邮编',
                key: 'zipCode',
                value: 'zipCode'
              },
              {
                title: '时区',
                key: 'timezone',
                value: 'timezone'
              },
              {
                title: '使用者类型',
                key: 'userType',
                value: 'userType'
              },
              {
                title: '使用者',
                key: 'user',
                value: 'user'
              },
              {
                title: '运营商',
                key: 'ispDomain',
                value: 'ispDomain'
              },
              {
                title: 'ASN',
                key: 'asn',
                value: 'asn'
              },
              {
                title: '组织信息',
                key: 'owner',
                value: 'owner'
              },
              {
                title: '行业',
                key: 'industry',
                value: 'industry'
              },
              {
                title: '应用场景',
                key: 'scene',
                value: 'scene'
              },
              {
                title: '管理员',
                key: 'staffNickname',
                value: 'staffNickname'
              },
              {
                title: '手机号',
                key: 'staffTelephone',
                value: 'staffTelephone'
              },
              {
                title: '邮箱',
                key: 'staffEmail',
                value: 'staffEmail'
              },
              {
                title: '来源',
                key: 'origin',
                value: 'origin'
              },
              ...customAttributeList.map(attr => {
                return {
                  title: attr.name,
                  key: `CUSTOM_ATTRIBUTE_${attr._id}`,
                  value: `CUSTOM_ATTRIBUTE_${attr._id}`
                };
              })
            ].filter(Boolean)
          }
        ]
      }
    ].filter(Boolean);

    return filters;
  };

  // 获取所有扩展搜索项
  getTotalExtendFilters = () => {
    const { customAttributeList, assetStats } = this.props;
    const tagFilterOptions = formatTreeSelectOption(_.get(assetStats, 'tag', []));
    // const areaFilterOptions = formatTreeSelectOption(_.get(assetStats, 'area', []));
    const organizationFilterOptions = formatTreeSelectOption(_.get(assetStats, 'organization', []));
    const locationFilterOptions = formatTreeSelectOption(_.get(assetStats, 'location', []));
    const assetCategoryFilterOptions = formatTreeSelectOption(
      _.get(assetStats, 'assetCategory', [])
    );
    const osFilterOptions = formatTreeSelectOption(_.get(assetStats, 'os', []));
    const serviceFilterOptions = formatTreeSelectOption(_.get(assetStats, 'service', []));
    const riskServiceFilterOptions = _.map(_.get(assetStats, 'riskService', []), i => ({
      key: `risk_${i}`,
      title: i,
      value: i
    }));
    const componentFilterOptions = _.map(
      _.get(assetStats, 'component', []),
      ({ _id: i, isDomestic }) => ({
        key: i,
        title: isDomestic ? `${i}(国产化)` : i,
        value: i
      })
    );
    const portFilterOptions = _.map(_.get(assetStats, 'port', []), ({ _id: i }) => ({
      key: i,
      title: i,
      value: i
    }));
    const riskPortFilterOptions = _.map(_.get(assetStats, 'riskPort', []), (i, index) => ({
      key: `1_${index}_$_${i}`,
      title: i,
      value: `1_${index}_$_${i}`
    }));

    const webWafFilterOptions = formatTreeSelectOption(_.get(assetStats, 'waf', []));
    const industryFilterOptions = formatTreeSelectOption(_.get(assetStats, 'industry', []));

    const vulFilterOptions = formatTreeSelectOption(_.get(assetStats, 'oneday', []));
    const originFilterOptions = formatTreeSelectOption(_.get(assetStats, 'origin', []));
    const ispDomainFilterOptions = formatTreeSelectOption(_.get(assetStats, 'ispDomain', []));
    const areaCodeFilterOptions = formatTreeSelectOption(_.get(assetStats, 'areaCode', []));
    const zipCodeFilterOptions = formatTreeSelectOption(_.get(assetStats, 'zipCode', []));
    const timezoneFilterOptions = formatTreeSelectOption(_.get(assetStats, 'timezone', []));
    const userFilterOptions = formatTreeSelectOption(_.get(assetStats, 'user', []));
    const userTypeFilterOptions = formatTreeSelectOption(_.get(assetStats, 'userType', []));
    const sceneFilterOptions = formatTreeSelectOption(_.get(assetStats, 'scene', []));
    const asnFilterOptions = formatTreeSelectOption(_.get(assetStats, 'asn', []));
    const ownerFilterOptions = formatTreeSelectOption(_.get(assetStats, 'owner', []));
    const staffNicknameFilterOptions = formatTreeSelectOption(
      _.get(assetStats, 'staffNickname', [])
    );
    const staffTelephoneFilterOptions = formatTreeSelectOption(
      _.get(assetStats, 'staffTelephone', [])
    );
    const staffEmailFilterOptions = formatTreeSelectOption(_.get(assetStats, 'staffEmail', []));

    const totalExtendFilters = [
      {
        title: '资产分类',
        key: 'assetCategory',
        type: TreeSelectFilterType,
        options: assetCategoryFilterOptions
      },
      {
        title: '资产类型',
        key: 'assetType',
        type: TreeSelectFilterType,
        options: [
          {
            title: 'IP',
            key: 'ip',
            value: 'ip'
          },
          {
            title: '网站',
            key: 'domain',
            value: 'domain'
          },
          {
            title: '其他',
            key: 'other',
            value: 'other'
          }
        ]
      },
      {
        title: '部门',
        key: 'organization',
        type: TreeSelectFilterType,
        options: organizationFilterOptions
      },
      {
        title: '地理位置',
        key: 'location',
        type: TreeSelectFilterType,
        options: locationFilterOptions
      },
      {
        title: '操作系统',
        key: 'os',
        type: TreeSelectFilterType,
        options: osFilterOptions
      },
      {
        title: '区域编码',
        key: 'areaCode',
        type: TreeSelectFilterType,
        options: areaCodeFilterOptions
      },
      {
        title: '邮编',
        key: 'zipCode',
        type: TreeSelectFilterType,
        options: zipCodeFilterOptions
      },
      {
        title: '时区',
        key: 'timezone',
        type: TreeSelectFilterType,
        options: timezoneFilterOptions
      },
      {
        title: '使用者',
        key: 'user',
        type: TreeSelectFilterType,
        options: userFilterOptions
      },
      {
        title: '使用者类型',
        key: 'userType',
        type: TreeSelectFilterType,
        options: userTypeFilterOptions
      },
      {
        title: '应用场景',
        key: 'scene',
        type: TreeSelectFilterType,
        options: sceneFilterOptions
      },
      {
        title: '行业',
        key: 'industry',
        type: TreeSelectFilterType,
        options: industryFilterOptions
      },
      {
        title: '运营商',
        key: 'ispDomain',
        type: TreeSelectFilterType,
        options: ispDomainFilterOptions
      },
      {
        title: 'ASN',
        key: 'asn',
        type: TreeSelectFilterType,
        options: asnFilterOptions
      },
      {
        title: '组织信息',
        key: 'owner',
        type: TreeSelectFilterType,
        options: ownerFilterOptions
      },
      {
        title: '端口',
        key: 'port',
        type: TreeSelectFilterType,
        options: [
          {
            title: '高危端口',
            key: 'riskPort',
            disableCheckbox: true,
            children: riskPortFilterOptions
          },
          {
            title: '其他端口',
            key: 'otherPort',
            disableCheckbox: true,
            children: portFilterOptions
          }
        ]
      },
      {
        title: '服务',
        key: 'service',
        type: TreeSelectFilterType,
        options: [
          {
            title: '高危服务',
            key: 'riskService',
            disableCheckbox: true,
            children: riskServiceFilterOptions
          },
          {
            title: '其他服务',
            key: 'otherService',
            disableCheckbox: true,
            children: serviceFilterOptions
          }
        ]
      },
      {
        title: '组件',
        key: 'component',
        type: TreeSelectFilterType,
        options: componentFilterOptions
      },
      {
        title: '防护信息',
        key: 'waf',
        type: TreeSelectFilterType,
        options: webWafFilterOptions
      },
      {
        title: '漏洞',
        key: 'oneday',
        type: TreeSelectFilterType,
        options: vulFilterOptions
      },
      {
        title: '标签',
        key: 'tag',
        type: TreeSelectFilterType,
        options: tagFilterOptions
      },
      {
        title: '管理员',
        key: 'staffNickname',
        type: TreeSelectFilterType,
        options: staffNicknameFilterOptions
      },
      {
        title: '手机号',
        key: 'staffTelephone',
        type: TreeSelectFilterType,
        options: staffTelephoneFilterOptions
      },
      {
        title: '邮箱',
        key: 'staffEmail',
        type: TreeSelectFilterType,
        options: staffEmailFilterOptions
      },
      {
        title: '来源',
        key: 'origin',
        type: TreeSelectFilterType,
        options: originFilterOptions
      },
      ...customAttributeList.map(attr => {
        const option = {
          title: attr.name,
          key: `CUSTOM_ATTRIBUTE_${attr._id}`,
          type: attr.type === 'string' ? InputFilterType : TreeSelectFilterType
        };
        if (attr.type !== 'string') {
          option.options = _.get(attr, 'options', []).map(i => ({
            title: i,
            key: i,
            value: i
          }));
        }
        return option;
      })
    ];

    return totalExtendFilters;
  };

  // 获取扩展搜索项
  getExtendFilters = () => {
    const { attributeFilter } = this.props;
    const { totalExtendFilters } = this.state;

    const filters = totalExtendFilters.filter(({ key }) =>
      _.includes(_.map(_.get(attributeFilter, 'moreAction.value'), 'value'), key)
    );

    return filters;
  };

  // 移除扩展筛选项，同时删除该项目筛选值
  removeExtendFilter = (item, e) => {
    e.stopPropagation();
    const key = _.get(item, 'key');
    if (!key) {
      return;
    }
    const { attributeFilter, setState } = this.props;
    const newAttributeFilter = _.omit(attributeFilter, ['moreAction', key]);
    newAttributeFilter.moreAction = {
      type: TreeSelectFilterType,
      value: _.filter(_.get(attributeFilter, 'moreAction.value'), item => item.value !== key)
    };
    setState({ attributeFilter: newAttributeFilter });
    this.setState({ activeFilterKey: '' });
  };

  recursiveNodes = (checkedNodes, pickParentNode) => {
    const nodes = [];
    _.forEach(checkedNodes, node => {
      if (pickParentNode || _.isEmpty(node.children)) {
        nodes.push(_.get(node, 'node.props'));
      }
      if (!_.isEmpty(node.children)) {
        nodes.push(...this.recursiveNodes(node.children, pickParentNode));
      }
    });
    return _.filter(nodes, Boolean);
  };

  onAttributeFilterValueChange = (item, rawValue, label, extra) => {
    const key = _.get(item, 'key');
    if (!key) {
      return;
    }
    let value = rawValue;
    //#region 处理地理位置筛选
    if (key === 'location') {
      // 获取所有叶子节点
      const leafNodes = this.recursiveNodes(extra.allCheckedNodes);
      value = _.map(leafNodes, node => {
        return {
          label: node.title,
          value: node.value,
          location: _.get(node, 'item.location', {})
        };
      });
    }
    //#endregion

    //#region 处理资产分类和部门
    const withParentNodeKeys = ['organization', 'assetCategory'];
    if (_.includes(withParentNodeKeys, key)) {
      const nodes = this.recursiveNodes(extra.allCheckedNodes, true);
      value = _.map(nodes, node => {
        return { label: node.title, value: node.value };
      });
    }
    //#endregion

    const { attributeFilter, setState } = this.props;
    let newAttributeFilter = {},
      newExtendKey;
    if (item.key === 'moreAction') {
      // 取消更多里的筛选项时，删除该项的筛选值
      const prevExtendKeys = _.map(_.get(attributeFilter, ['moreAction', 'value']), 'value');
      const currentExtendKeys = _.map(value, 'value');
      const removedExtendKeys = _.difference(prevExtendKeys, currentExtendKeys);
      newAttributeFilter = _.omit(attributeFilter, removedExtendKeys.concat(key));

      // 展开新增的筛选项
      newExtendKey = _.difference(currentExtendKeys, prevExtendKeys)[0];
    } else {
      newAttributeFilter = _.omit(attributeFilter, key);
    }
    newAttributeFilter[key] = {
      type: item.type,
      value
    };

    setState({
      attributeFilter: newAttributeFilter,
      pagaition: {
        page: 1,
        pageSize: 10
      }
    });

    // 延迟更新一次，避免下拉框的ref为空，延迟不能设置太短，否则父组件可能未渲染
    if (newExtendKey) {
      this.expanTimeoutTimer = setTimeout(() => {
        this.setState({ activeFilterKey: newExtendKey });
      }, 25);
    }
  };

  renderAttributeFilterItem = (item = {}, props = {}) => {
    const { attributeFilter } = this.props;
    const { activeFilterKey } = this.state;
    return (
      <AttributeFilterItem
        {...item}
        {...props}
        key={item.key}
        value={_.get(attributeFilter, [item.key, 'value'])}
        onChange={(...args) => this.onAttributeFilterValueChange(item, ...args)}
        active={item.key === activeFilterKey}
        onClick={() => {
          if (this.state.activeFilterKey !== item.key) {
            this.setState({ activeFilterKey: item.key });
          }
        }}
      />
    );
  };

  render() {
    const { criteriaFilters } = this.state;
    const extendFiltersFilters = this.getExtendFilters();
    return (
      <div className="attribute-filter">
        <div className="criteria-filter">
          {criteriaFilters.map(item => this.renderAttributeFilterItem(item))}
        </div>
        <div
          id={ExtendAttributeFilterId}
          className={cn('extend-filter', { empty: !extendFiltersFilters.length })}
        >
          {extendFiltersFilters.map(item =>
            this.renderAttributeFilterItem(item, {
              isExtend: true,
              onRemoveExtend: e => this.removeExtendFilter(item, e)
            })
          )}
        </div>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    tags: _.get(state, 'tag.tags', []),
    attributeFilter: _.get(state, 'assetManage.attributeFilter', {}),
    customAttributeList: _.get(state, 'assetManage.customAttributeList', []),
    organizationTree: _.get(state, 'assetManage.organizationTree', []),
    assetCategoryTree: _.get(state, 'assetManage.assetCategoryTree', []),
    areaList: _.get(state, 'assetManage.areaList', []),
    siteAttributeStats: _.get(state, 'assetManage.siteAttributeStats', []),
    assetStats: _.get(state, 'assetManage.assetStats', {}),
    modules: _.get(state, 'auth.cert.modules', [])
  };
};

const mapDispatchToProps = dispatch => {
  return {
    ...bindActionCreators(assetManageActions, dispatch)
  };
};
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(AttributeFilter);
